<?php

namespace App\Transformers;

use App\Models\Order;
use App\Models\Product;

class ProductTransformer extends BaseTransformer
{
    protected $availableIncludes = ['schedules'];

    public function transform(Product $model)
    {
        $data = [
            'id' => $model->id,
            'title' => $model->title,                           #标题
            'shop_id' => $model->shop_id,                       #商店id
            'shop_name' => $model->shop->name,                  #商店名称
            'subtitle' => $model->subtitle,                     #副标题
            'image' => image_url($model->image),                #主图
            'contact_phone' => $model->contact_phone,           #联系电话
            'content' => $model->content,        #内容
            'pictures' => image_url($model->pictures),        #内容(图)
            'service_time' => $model->service_time,             #服务时间
            'price' => $this->getFirstSchedulePrice($model),
            'stock_amount' => $model->stock_amount,             #库存
            'view_amount' => $model->view_amount,               #浏览量
            'sell_amount' => $model->order
                ->where('status', Order::STATUS_FINISH)
                ->where('refund_status', Order::REFUND_STATUS_PENDING)
                ->count(),                                      #成交量
            'province' => $model->province,                     #省
            'city' => $model->city,                             #市
            'district' => $model->district,                     #区
            'address' => $model->address,                       #详细地址
            'longitude' => $model->longitude,                   #经度
            'latitude' => $model->latitude,                     #纬度
            'is_show' => $model->is_show,                     #纬度
            'created_at' => $model->created_at->toDateTimeString(),
        ];

        return $this->_select($data);
    }

    public function includeSchedules(Product $model)
    {
        return $this->collection($model->schedules, new ScheduleTransformer());
    }

    private function getFirstSchedulePrice(Product $model)
    {
        $schedules = $model->schedules->first();

        if ($schedules) {
            return getMoneyFormat($schedules->price);
        } else {
            return '0.00';
        }
    }
}
